﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Configuration;

namespace BobbyCore
{
    public class Operation
    {
        /// <summary>
        /// 数据库类型
        /// </summary>
        DataBaseType dbType = (DataBaseType)Enum.Parse(typeof(DataBaseType), ConfigurationManager.AppSettings["dbType"]);
        DbConnection mycon;
        DataSet ds;
        /// <summary>
        /// 类的初始化
        /// </summary>
        public Operation()
        {
            mycon = MyCore.CreateConnection(dbType);
            ds = new DataSet();

        }
        #region   打开数据库连接
        /// <summary>
        /// 打开数据库连接.
        /// </summary>
        private void Open()
        {
            // 打开数据库连接
            if (mycon.State == System.Data.ConnectionState.Closed && mycon!=null)
                mycon.Open();

        }
        #endregion

        #region  关闭连接
        /// <summary>
        /// 关闭数据库连接
        /// </summary>
        public void Close()
        {
            if (mycon.State == System.Data.ConnectionState.Open&&mycon != null)
                mycon.Close();
        }
        #endregion

        #region 释放数据库连接资源
        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            if (mycon != null)
            {
                mycon.Dispose();
                mycon= null;
            }
        }
        #endregion
        /// <summary>
        /// DataSet数据集（含参）
        /// </summary>
        /// <param name="Type"></param>
        /// <param name="test"></param>
        /// <param name="pars"></param>
        /// <param name="dbType"></param>
        /// <param name="con"></param>
        /// <returns></returns>
        public DataSet DS(CommandType Type, string Text, DbParameter[] Pars)
        {
            DbCommand mycmd = MyCore.CreateCommand(Type, Text, Pars, dbType, mycon);
            DbDataAdapter myda = MyCore.CreateDataAdapter(mycmd, dbType);
            myda.Fill(ds);
            return ds;
        }
        /// <summary>
        /// DataSet数据集（无参）
        /// </summary>
        /// <param name="Type"></param>
        /// <param name="Text"></param>
        /// <returns></returns>
        public DataSet DS(CommandType Type, string Text)
        {
            
            DbCommand mycmd = MyCore.CreateCommand(Type, Text, dbType, mycon);
            DbDataAdapter myda = MyCore.CreateDataAdapter(mycmd, dbType);
            this.Open();
            myda.Fill(ds);
            this.Close();
            return ds;
        }
        /// <summary>
        /// 插入|删除|更新（无参）
        /// </summary>
        /// <param name="Type"></param>
        /// <param name="Text"></param>
        /// <param name="Pars"></param>
        /// <returns></returns>
        public int ExNoQuery(CommandType Type, string Text,ref DbTransaction tr)
        {
            int result =-1;
            DbConnection localconnection = null;
            if (tr == null)
            {
                localconnection = mycon;
                localconnection.Open();
                tr = localconnection.BeginTransaction();

            }
            else
            {
                localconnection = tr.Connection;
            }

            try
            {

                DbCommand mycmd = MyCore.CreateCommand(Type, Text, dbType, localconnection);
                mycmd.Transaction = tr;
                result = mycmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw new Exception("错误提示：\n" + ex.Message);
            }
            finally
            {
                if (((localconnection != null) && (localconnection.State == ConnectionState.Open)) && (tr == null))
                {
                    localconnection.Close();
                }
            }
            return result;
        }
        /// <summary>
        /// 插入|删除|更新（有参）
        /// </summary>
        /// <param name="Type"></param>
        /// <param name="Text"></param>
        /// <param name="Pars"></param>
        /// <param name="tr"></param>
        /// <returns></returns>
        public int ExNoQuery(CommandType Type, string Text,DbParameter[] Pars,ref DbTransaction tr)
        {
                int result =-1;
                DbConnection localconnection = null;
                if (tr == null)
                {
                    localconnection = mycon;
                    localconnection.Open();
                    tr = localconnection.BeginTransaction();
                }
                else
                {
                    localconnection = tr.Connection;
                }
     
            try
            {

                DbCommand mycmd = MyCore.CreateCommand(Type, Text, Pars, dbType, localconnection);
                mycmd.Transaction = tr;
               result=mycmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw new Exception("错误提示：\n" + ex.Message);
            }
            finally
            {
                if (((localconnection != null) && (localconnection.State == ConnectionState.Open)) && (tr == null))
                {
                    localconnection.Close();
                }
            }
           return result;
        }
        public int ExNoQuery(CommandType Type, string Text, DbParameter[] Pars)
        {
            int result = -1;
            try
            {
                DbCommand mycmd = MyCore.CreateCommand(Type, Text, Pars, dbType,mycon);
                result = mycmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw new Exception("错误提示：\n" + ex.Message);
            }
            finally
            {
                    mycon.Close();
            }
            return result;
        }
        /// <summary>
        /// 插入|删除|更新（无事务）
        /// </summary>
        /// <param name="Type"></param>
        /// <param name="Text"></param>
        /// <param name="Pars"></param>
        /// <param name="tr"></param>
        /// <returns></returns>
        public int ExNoQuery(CommandType Type, string Text)
        {
            int result = -1;
            try
            {

                DbCommand mycmd = MyCore.CreateCommand(Type, Text, dbType,mycon);
                result = mycmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw new Exception("错误提示：\n" + ex.Message);
            }
            finally
            {
                mycon.Close();
            }
            return result;
        }
        /// <summary>
        /// 获取第一行第一列（有参）
        /// </summary>
        /// <param name="Type"></param>
        /// <param name="Text"></param>
        /// <param name="Pars"></param>
        /// <returns></returns>
        public object ExScalar(CommandType Type, string Text, DbParameter[] Pars)

        {
            object result;
            DbCommand mycmd = MyCore.CreateCommand(Type, Text, Pars, dbType, mycon);
            mycon.Open();
            result = mycmd.ExecuteScalar();
            mycon.Close();
            return result;
        }
        /// <summary>
        /// 获取第一行第一列（无参）
        /// </summary>
        /// <param name="Type"></param>
        /// <param name="Text"></param>
        /// <returns></returns>
        public object ExScalar(CommandType Type, string Text)
        {

            object result;
            DbCommand mycmd = MyCore.CreateCommand(Type, Text, dbType, mycon);
            mycon.Open();
            result = mycmd.ExecuteScalar();
            mycon.Close();
            return result;
        }

   
     /// <summary>
      ///  获取泛型集合
     /// </summary>
     /// <typeparam name="T"></typeparam>
     /// <param name="dataSet"></param>
     /// <param name="tableIndex"></param>
     /// <returns></returns>
        public List<T> GetList<T>(DataSet dataSet, int tableIndex)
        {
          //  return DatasetToList.DataSetToList<T>(dataSet, tableIndex).Cast<T>().ToList<T>();
            return DatasetToList.DataSetToList<T>(dataSet, tableIndex);
        }
        /// <summary>
        /// Dataset to list(SQL中无参数)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Type"></param>
        /// <param name="Text"></param>
        /// <returns></returns>
        public List<T> ToList<T>(CommandType Type, string Text)
        {

            DataSet set = this.DS(Type, Text);
            return this.GetList<T>(set, 0);
        }
        /// <summary>
        /// Dataset to list(SQL中有参数)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Type"></param>
        /// <param name="Text"></param>
        /// <returns></returns>
        public List<T> ToList<T>(CommandType Type, string Text, DbParameter[] Pars)
        {

            DataSet set = this.DS(Type, Text, Pars);
            return this.GetList<T>(set, 0);
        }
    }
}
